package com.xuzz.study.aop.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * @author xuzz
 * @description
 * @date 2019-12-04 11:29
 */
public class MathCGLIBAOP implements MethodInterceptor {

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("before");
        Object result = methodProxy.invokeSuper(o,objects);
        System.out.println("after");
        return result;
    }

    public static <T> T getInstance(Class<T> clazz, Constructor ctr, Object[] args)
    {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new MathCGLIBAOP());

        if(null==ctr)
        {
            return (T)enhancer.create();
        }
        else
        {
            return (T)enhancer.create(ctr.getParameterTypes(),args);
        }
    }
}
